package com.chc.util;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.chc.util.Constant.*;

public class LoginFilter implements Filter {
	private Set<String> allowSet = new HashSet<String>();
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		allowSet.add("/");
		allowSet.add("/index.jsp");
		allowSet.add("/ag/login");
		allowSet.add("/login");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		
		String path = req.getServletPath();
		
		if(path.startsWith("/resources") || path.startsWith("/download") || allowSet.contains(path)
				|| req.getSession().getAttribute(Constant.KEY_USER_INFO)!=null) {
			chain.doFilter(request, response);
		}else if(path.startsWith("/ag/")){
			String token=req.getParameter("token");
			String paramId=req.getParameter("id");
			String id=null;
			if (token!=null&& paramId!=null){
				id=(String)req.getServletContext().getAttribute(token);
				
				if (id==null){
					ServiceResult<Void> r=new ServiceResult<Void>();
					r.setCode(ServiceResult.CODE_NOT_COMPLETE);
					r.setMsg("期限が切れています。もう一度ログインしてください。");
					WebUtil.writeJsonStr((HttpServletResponse)response, r);
				} else if(!id.equals(paramId)) {
					ServiceResult<Void> r=new ServiceResult<Void>();
					r.setCode(ServiceResult.CODE_NOT_COMPLETE);
					r.setMsg("この操作を行うことができません。");
					WebUtil.writeJsonStr((HttpServletResponse)response, r);
				} else {
					chain.doFilter(request, response);
				}
			} else {
				ServiceResult<Void> r=new ServiceResult<Void>();
				r.setCode(ServiceResult.CODE_NOT_COMPLETE);
				r.setMsg("この操作を行うことができません。");
				WebUtil.writeJsonStr((HttpServletResponse)response, r);
			}

		} else {
			String responseDataType = req.getParameter("respDataType");
			if(!"json".equalsIgnoreCase(responseDataType)) {
				req.setAttribute("errorMsg", "ログインしてください");
				req.getRequestDispatcher("/index.jsp").forward(request, response);	
			} else {
				ServiceResult<Void> r=new ServiceResult<Void>();
				r.setCode(ServiceResult.CODE_NOT_COMPLETE_SESSION_EXPIRED);
				r.setMsg("ログインしてください");
				WebUtil.writeJsonStr((HttpServletResponse)response, r);
			}
			
		}
	}

	@Override
	public void destroy() {
		
	}

}
